import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import AsyncStorage from "@react-native-async-storage/async-storage";

// 定义接口响应数据结构
interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: "http://localhost:3000", // 设置基础URL
  timeout: 10000, // 请求超时时间
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
request.interceptors.request.use(
  async (config: AxiosRequestConfig) => {
    try {
      const token = await AsyncStorage.getItem("token");
      if (token && config.headers) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    } catch (error) {
      console.error("获取token失败:", error);
      return config;
    }
  },
  (error) => {
    console.error("请求错误:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  <T>(response: AxiosResponse<ApiResponse<T>>) => {
    const { data } = response;
    if (data.code === 200) {
      return data.data;
    }
    return Promise.reject(new Error(data.message || "请求失败"));
  },
  (error) => {
    let errorMessage = "网络异常，请检查网络是否正常";

    if (error.response) {
      switch (error.response.status) {
        case 401:
          errorMessage = "未授权，请重新登录";
          // 这里可以添加跳转到登录页的逻辑
          break;
        case 403:
          errorMessage = "权限不足";
          break;
        case 404:
          errorMessage = "请求的资源不存在";
          break;
        case 500:
          errorMessage = "服务器错误";
          break;
        default:
          errorMessage = `服务器响应错误(${error.response.status})`;
      }
    } else if (error.message.includes("timeout")) {
      errorMessage = "请求超时！请检查网络是否正常";
    }

    console.error(errorMessage);
    return Promise.reject(new Error(errorMessage));
  }
);

// 封装GET请求
export function get<T>(url: string, params?: Record<string, unknown>): Promise<T> {
  return request.get<unknown, T>(url, { params });
}

// 封装POST请求
export function post<T>(url: string, data?: Record<string, unknown>): Promise<T> {
  return request.post<unknown, T>(url, data);
}

// 封装PUT请求
export function put<T>(url: string, data?: Record<string, unknown>): Promise<T> {
  return request.put<unknown, T>(url, data);
}

// 封装DELETE请求
export function del<T>(url: string): Promise<T> {
  return request.delete<unknown, T>(url);
}

export default request
